import { HttpContext } from '@angular/common/http';
import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { LoadingService } from '@delon/abc/loading';
import { LoadingType } from '@delon/abc/loading/loading.types';
import { STChange, STColumn, STComponent, STPage } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { ALLOW_ANONYMOUS } from '@delon/auth';
import { SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { finalize } from 'rxjs/operators';
import { Api } from 'src/app/shared/api/api';
import { BaseAbilityComponent } from 'src/app/shared/base.ability.component';
import { DELETED_STATUS_ENUM, USER_LABEL_ENUM, USER_LABEL_TAG } from 'src/app/shared/constant/common-constant';
import { ResponseCode } from 'src/app/shared/response.code';
import { AbilityService } from 'src/app/shared/service/ability.service';

import { ComponentsUserChangeComponent } from './user-change.component';
import { ComponentsUserDetailComponent } from './user-detail.component';
import { UserEditComponent } from './user-edit.component';
import { ComponentsXlsxImportComponent } from './user-xls-expert.component';

interface TagSelectDemoItem {
  id: number;
  text: string;
  value: boolean;
}

@Component({
  selector: 'app-system-user-sea',
  templateUrl: './user-sea.component.html'
})
export class SystemUserSeaComponent extends BaseAbilityComponent implements OnInit, OnDestroy {
  params: any = {
    status: 3,
    industry: '',
    xs_source: '',
    last_flow_up_name: '',
    userId: localStorage.getItem('user_id'),
    sys_role_id: localStorage.getItem('sys_role_id')
  };
  url = Api.BaseCustomerApi;
  fenpeiList: any;
  searchParams: any = {};
  data: any;
  page: any = {
    data: [],
    current: 1,
    total: 1,
    size: 10
  };
  pagination: STPage = {
    front: false,
    pageSizes: [10, 20, 30, 40, 50],
    total: true,
    showSize: true,
    showQuickJumper: true
  };
  categories: TagSelectDemoItem[] = [
    { id: 0, text: '全部', value: false },
    { id: 1, text: '广告', value: false },
    { id: 2, text: '客户介绍', value: false },
    { id: 3, text: '地推', value: false },
    { id: 3, text: '寻客宝', value: false },
    { id: 3, text: '其他', value: false }
  ];
  vCategories: TagSelectDemoItem[] = [
    { id: 0, text: '全部', value: false },
    { id: 1, text: '农林牧渔', value: false },
    { id: 2, text: '采矿业', value: false },
    { id: 3, text: '制造业', value: false },
    { id: 4, text: '水电燃气', value: false },
    { id: 5, text: '建筑业', value: false },
    { id: 6, text: '批发零售', value: false },
    { id: 7, text: '交通运输', value: false },
    { id: 8, text: '住宿餐饮', value: false },
    { id: 9, text: '互联网', value: false },
    { id: 10, text: '金融业', value: false },
    { id: 11, text: '房地产业', value: false },
    { id: 12, text: '商务服务', value: false },
    { id: 13, text: '科技服务', value: false },
    { id: 14, text: '水利公共', value: false },
    { id: 15, text: '居民服务', value: false },
    { id: 16, text: '教育', value: false },
    { id: 17, text: '公共卫生', value: false },
    { id: 18, text: '文体娱乐', value: false },
    { id: 19, text: '公共机构', value: false },
    { id: 20, text: '国际组织', value: false }
  ];
  searchSchema: SFSchema = {
    properties: {
      username: {
        type: 'string',
        title: '法人',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      phone: {
        type: 'string',
        title: '公司名称',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      name: {
        type: 'string',
        title: '公司地址',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      email: {
        type: 'string',
        title: '电话号码',
        ui: {
          acl: { ability: ['query'] }
        }
      },
      label: {
        type: 'string',
        title: '标签',
        default: '',
        enum: USER_LABEL_ENUM,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      },
      deleted: {
        type: 'string',
        title: '状态',
        default: false,
        enum: DELETED_STATUS_ENUM,
        ui: {
          widget: 'select',
          acl: { ability: ['query'] }
        }
      }
    }
  };

  @ViewChild('st', { static: true }) st!: STComponent;
  columns: STColumn[] = [
    { title: '编号', index: 'id', type: 'checkbox' },
    {
      title: '法人',
      index: 'name',
      sort: {
        compare: (a, b) => a.name.length - b.name.length
      },
      filter: {
        type: 'keyword',
        placeholder: '输入后按回车搜索',
        fn: (filter, record) => !filter.value || record.name.indexOf(filter.value) !== -1
      }
    },
    {
      title: '公司名称',
      index: 'company_name',
      sort: {
        compare: (a, b) => a.company_name.length - b.company_name.length
      },
      filter: {
        type: 'keyword',
        placeholder: '输入后按回车搜索',
        fn: (filter, record) => !filter.value || record.company_name.indexOf(filter.value) !== -1
      }
    },
    {
      title: '公司地址',
      index: 'company_address',
      sort: {
        compare: (a, b) => a.company_address.length - b.company_address.length
      },
      filter: {
        type: 'keyword',
        placeholder: '输入后按回车搜索',
        fn: (filter, record) => !filter.value || record.company_address.indexOf(filter.value) !== -1
      }
    },
    {
      title: '电话号码',
      index: 'phone',
      sort: {
        compare: (a, b) => a.phone.length - b.phone.length
      },
      filter: {
        type: 'keyword',
        placeholder: '输入后按回车搜索',
        fn: (filter, record) => !filter.value || record.phone.indexOf(filter.value) !== -1
      }
    },
    {
      title: '行业',
      width: 60,
      index: 'industry',
      type: 'badge',
      filter: {
        menus: [
          { text: '全部', value: '' },
          { text: '农林牧渔', value: '农林牧渔' },
          { text: '采矿业', value: '采矿业' },
          { text: '制造业', value: '制造业' },
          { text: '水电燃气', value: '水电燃气' },
          { text: '建筑业', value: '建筑业' },
          { text: '水电燃气', value: '水电燃气' },
          { text: '批发零售', value: '批发零售' },
          { text: '交通运输', value: '交通运输' },
          { text: '住宿餐饮', value: '住宿餐饮' },
          { text: '互联网', value: '互联网' },
          { text: '金融业', value: '金融业' },
          { text: '房地产业', value: '房地产业' },
          { text: '商务服务', value: '商务服务' },
          { text: '科技服务', value: '科技服务' },
          { text: '水利公共', value: '水利公共' },
          { text: '居民服务', value: '居民服务' },
          { text: '教育', value: '教育' },
          { text: '公共卫生', value: '公共卫生' },
          { text: '文体娱乐', value: '文体娱乐' },
          { text: '公共机构', value: '公共机构' },
          { text: '国际组织', value: '国际组织' }
        ],
        fn: (filter, record) => !filter.value || record.industry.indexOf(filter.value) !== -1
      }
    },
    {
      title: '跟进人',
      width: 60,
      index: 'last_flow_up_name',
      sort: {
        compare: (a, b) => a.last_flow_up_name.length - b.last_flow_up_name.length
      },
      filter: {
        type: 'keyword',
        placeholder: '输入后按回车搜索',
        fn: (filter, record) => !filter.value || record.last_flow_up_name.indexOf(filter.value) !== -1
      }
    },
    { title: '跟进记录', width: 60, index: 'last_flow_up_record' },
    { title: '跟进时间', width: 60, index: 'last_flow_up_time' },
    { title: '标签', width: 60, index: 'label', type: 'tag', tag: USER_LABEL_TAG },
    {
      title: '来源',
      width: 60,
      index: 'xs_source',
      type: 'badge',
      filter: {
        menus: [
          { text: '全部', value: '' },
          { text: '广告', value: '广告' },
          { text: '客户介绍', value: '客户介绍' },
          { text: '地推', value: '地推' },
          { text: '寻客宝', value: '寻客宝' },
          { text: '其他', value: '其他' }
        ],
        fn: (filter, record) => !filter.value || record.xs_source.indexOf(filter.value) !== -1
      }
    },
    {
      title: '状态',
      width: 60,
      type: 'badge',
      index: 'customer_status',
      badge: {
        正常: { text: '正常', color: 'success' },
        过期: { text: '过期', color: 'error' },
        3: { text: 'Processing', color: 'processing' },
        4: { text: 'Default', color: 'default' },
        5: { text: 'Warning', color: 'warning' }
      },
      filter: {
        menus: [
          { text: '正常', value: '正常' },
          { text: '过期', value: '过期' }
        ],
        fn: (filter, record) => !filter.value || record.customer_status.indexOf(filter.value) !== -1
      }
    },
    {
      title: '操作',
      buttons: [
        {
          text: '详情',
          type: 'modal',
          modal: {
            component: ComponentsUserDetailComponent
          },
          click: () => {
            this.st.reload();
          }
        },
        {
          text: '编辑',
          type: 'modal',
          modal: {
            component: UserEditComponent
          },
          click: () => {
            this.st.reload();
          }
        },
        {
          text: '取回',
          click: (record: any) => {
            this.getOut(record);
          }
        },
        {
          text: '删除',
          click: (record: any) => {
            this.delete(record);
          },
          iif: () => localStorage.getItem('sys_role_id') === '1',
          iifBehavior: 'hide'
        }
      ]
    }
  ];

  constructor(
    protected http: _HttpClient,
    private modal: ModalHelper,
    private modalService: NzModalService,
    private msg: NzMessageService,
    private loadingSrv: LoadingService,
    route: ActivatedRoute,
    ability: AbilityService,
    private xlsx: XlsxService,
    private cdr: ChangeDetectorRef
  ) {
    super(route, ability);
  }

  ngOnInit() {
    super.initAbilities();
    this.searchParams = { deleted: false };
  }
  ngOnDestroy(): void {
    super.clearAbilities();
  }

  change(e: STChange) {
    if (e.checkbox) {
      this.fenpeiList = e.checkbox;
    }
    console.log(this.fenpeiList);
  }
  search(event: any) {
    if (event) {
      if (event.username) {
        this.searchParams.username = event.username;
      } else {
        delete this.searchParams.username;
      }
      if (event.phone) {
        this.searchParams.phone = event.phone;
      } else {
        delete this.searchParams.phone;
      }
      if (event.name) {
        this.searchParams.name = event.name;
      } else {
        delete this.searchParams.name;
      }
      if (event.email) {
        this.searchParams.email = event.email;
      } else {
        delete this.searchParams.email;
      }
      if (event.label) {
        this.searchParams.label = event.label;
      } else {
        delete this.searchParams.label;
      }
      if (event.deleted !== null) {
        this.searchParams.deleted = event.deleted;
      } else {
        delete this.searchParams.deleted;
      }
    }
  }

  show(type: LoadingType) {
    this.loadingSrv.open({ type });
  }
  add() {
    this.modal.createStatic(UserEditComponent).subscribe(() => this.st.reload());
  }
  fenpei() {
    this.modalService.confirm({
      nzTitle: '确定删除吗?',
      nzContent: '<b style="color: red;">注意：此删除不可找回！！！</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http
          .post(Api.BaseDeleteCustomerApi, this.fenpeiList, {}, { context: new HttpContext().set(ALLOW_ANONYMOUS, true) })
          .subscribe((res: any) => {
            if (res) {
              if (res.code === ResponseCode.SUCCESS) {
                this.st.reload();
                this.msg.success('删除成功');
              } else {
                this.msg.warning(res.message);
              }
            } else {
              this.msg.error('删除失败，未知错误');
            }
          }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  insert() {
    this.modal.createStatic(ComponentsXlsxImportComponent).subscribe(() => this.st.reload());
  }
  delete(record: any) {
    this.modalService.confirm({
      nzTitle: '确定删除该客户吗?',
      nzContent: '<b style="color: red;">注意：此删除不可找回！！！</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http
          .post(
            Api.BaseDeleteCustomerApi,
            [
              {
                id: record.id
              }
            ],
            {},
            { context: new HttpContext().set(ALLOW_ANONYMOUS, true) }
          )
          .subscribe((res: any) => {
            if (res) {
              if (res.code === ResponseCode.SUCCESS) {
                this.st.reload();
                this.msg.success('删除成功');
              } else {
                this.msg.warning(res.message);
              }
            } else {
              this.msg.error('删除失败，未知错误');
            }
          }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  getOut(record: any) {
    this.modalService.confirm({
      nzTitle: '确定取回线索吗?',
      nzContent: '<b style="color: red;">如果您确定公海线索会回到线索中</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () =>
        this.http
          .post(
            Api.BaseCustomerUpdateStatusApi,
            {
              id: record.id,
              status: 1
            },
            { id: record.id, status: 1 },
            { context: new HttpContext().set(ALLOW_ANONYMOUS, true) }
          )
          .subscribe((res: any) => {
            if (res) {
              if (res.code === ResponseCode.SUCCESS) {
                this.st.reload();
                this.msg.success('取回成功');
                this.getMyUser(record);
              } else {
                this.msg.warning(res.message);
              }
            } else {
              this.msg.error('取回失败，未知错误');
            }
          }),
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }
  getMyUser(record: any) {
    (record.last_flow_up_name = localStorage.getItem('user_name')),
      this.http
        .post(
          Api.BaseUpdateCustomerApi,
          [record],
          {},
          {
            headers: {
              Authorization: 'Bearer dGVzdDp0ZXN0'
            },
            context: new HttpContext().set(ALLOW_ANONYMOUS, true)
          }
        )
        .subscribe((res: any) => {
          if (res && res.code === ResponseCode.SUCCESS) {
            this.msg.success('分配成功');
          }
        });
  }
}
